﻿using FirstHomeWork.SqlServer;
using FirstHomeWork.Utility;
using System;
using System.IO;
using System.Text;
using System.Threading.Tasks;

namespace FirstHomeWork.Common
{
    public class CreateModelComm
    {
        /// <summary>
        /// 创建 Model 代码
        /// </summary>
        /// <param name="TableName">表名称</param>
        /// <param name="Temp">路径</param>
        /// <returns></returns>
        public void CreateModelCode(string TableName, string Temp, string path)
        {
            SqlServerHelper sqlServerHelper = new SqlServerHelper();

            var _Cols = sqlServerHelper.GetColsByTableName(TableName);


            var _Code = Temp.ToString();
            var _ClassName = TableName;
            var _Fields = new StringBuilder();

            foreach (var item in _Cols)
            {
                var _Type = string.Empty;
                var _Key = item.ColIsKey;
                switch (item.ColType)
                {
                    case "bigint":
                        _Type = item.ColIsNull == 0 ? "long" : "long?";
                        break;
                    case "datetime":
                        _Type = item.ColIsNull == 0 ? "DateTime" : "DateTime?";
                        break;
                    case "uniqueidentifier":
                        _Type = _Key == 1 ? "Guid" : "Guid?";
                        break;
                    case "bit":
                    case "int":
                        _Type = item.ColIsNull == 0 ? "int" : "int?";
                        break;
                    case "float":
                        _Type = item.ColIsNull == 0 ? "float" : "float?";
                        break;
                    case "money":
                        _Type = item.ColIsNull == 0 ? "double" : "double?";
                        break;
                    case "decimal":
                    case "numeric":
                        _Type = item.ColIsNull == 0 ? "decimal" : "decimal?";
                        break;
                    default:
                        _Type = "string";
                        break;
                }

                if (_Key == 1)
                {
                    _Fields.Append($@"
        /// <summary>
        /// {item.ColRemark ?? item.ColName} 
        /// </summary>
");
                }
                else
                {
                    if (item.ColName.Contains("_CreateTime") && _Type == "DateTime?")
                    {
                        _Fields.Append($@"
        /// <summary>
        /// 创建时间
        /// </summary>
");
                    }
                    else
                    {

                        if (string.IsNullOrWhiteSpace(item.ColRemark))
                        {
                            _Fields.Append($@"
        /// <summary>
        /// {item.ColName}
        /// </summary>
");
                        }
                        else
                        {
                            _Fields.Append($@"
        /// <summary>
        /// {item.ColRemark} 
        /// </summary>
");
                        }

                    }
                }
                if (_Key == 1 && (_Type == "Guid" || _Type == "Guid?"))
                {
                    _Fields.Append($"\tpublic {_Type} {item.ColName} {{ get; set; }} = Guid.Empty;\r\n");

                }
                else
                {

                    _Fields.Append($"\tpublic {_Type} {item.ColName} {{ get; set; }}\r\n");
                }
            }

            _Code = _Code.Replace("<#ClassName#>", _ClassName);
            _Code = _Code.Replace("<#TableName#>", TableName);
            _Code = _Code.Replace("<#Fields#>", _Fields.ToString());

            path = Path.Combine(path, @"Content\Model");

            if (!Directory.Exists(path))
                Directory.CreateDirectory(path);
            File.WriteAllText($"{path}/{TableName}Model.cs", _Code, Encoding.UTF8);

        }



        /// <summary>
        /// 异步批量生成实体模型
        /// </summary>
        /// <param name="TableName">表名称</param>
        /// <param name="IsCreateAll">是否生成全部（默认不生成全部表模型）</param>
        /// <returns></returns>
        public async Task SaveTask(string TableName, bool IsCreateAll = false)
        {
            SqlServerHelper sqlServerHelper = new SqlServerHelper();

            var tableModels = sqlServerHelper.GetAllTable();
            await Task.Run(() =>
            {
                string filePath = AppDomain.CurrentDomain.BaseDirectory;
                var TempUrl = Path.Combine(filePath, @"Template\Model\Model.txt");
                var Template = File.ReadAllText(TempUrl, Encoding.UTF8);
                if (IsCreateAll)
                {
                    foreach (var item in tableModels)
                    {
                        CreateModelCode(item.Table_Name, Template, filePath);
                    }
                }
                else
                {
                    CreateModelCode(TableName, Template, filePath);
                }
                Task.Delay(3000);

            });


        }

        /// <summary>
        /// 批量生成实体模型
        /// </summary>
        /// <param name="TableName">表名称</param>
        /// <param name="IsCreateAll">是否生成全部（默认不生成全部表模型）</param>
        /// <returns></returns>
        [UserCreateFile]
        public void Save(string TableName, bool IsCreateAll = false)
        {
            SqlServerHelper sqlServerHelper = new SqlServerHelper();

            var tableModels = sqlServerHelper.GetAllTable();

            string filePath = AppDomain.CurrentDomain.BaseDirectory;
            var TempUrl = Path.Combine(filePath, @"Template\Model\Model.txt");
            var Template = File.ReadAllText(TempUrl, Encoding.UTF8);
            if (IsCreateAll)
            {
                foreach (var item in tableModels)
                {
                    CreateModelCode(item.Table_Name, Template, filePath);
                }
            }
            else
            {
                CreateModelCode(TableName, Template, filePath);
            }


        }
    }
}
